package org.example.ipersistent.utils;

import com.alibaba.druid.pool.DruidDataSource;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.example.ipersistent.pojo.Configuration;

import java.io.InputStream;
import java.util.List;
import java.util.Properties;

public class XmlConfigBuilder {

  private Configuration configuration;

  public XmlConfigBuilder(){
    this.configuration = new Configuration();
  }

  /**
   * 使用dom4j+xpath解析配置文件，封装容器对象
   * @param inputStream
   * @return
   */
  public Configuration parse(InputStream inputStream) throws DocumentException {
    Document document = new SAXReader().read(inputStream);
    Element root = document.getRootElement();
    // 解析数据源信息，创建数据源对象
    List<Element> propertyList = root.selectNodes("//property");
    Properties properties = new Properties();
    for (Element property : propertyList) {
      String name = property.attributeValue("name");
      String value = property.attributeValue("value");
      properties.setProperty(name,value);
    }
    DruidDataSource dataSource = new DruidDataSource();
    dataSource.setDriverClassName(properties.getProperty("driverClassName"));
    dataSource.setUrl(properties.getProperty("url"));
    dataSource.setUsername(properties.getProperty("username"));
    dataSource.setPassword(properties.getProperty("password"));
    configuration.setDataSource(dataSource);
    // 解析映射配置文件，封装MappedStatement对象
    List<Element> mapperList = root.selectNodes("//mapper");
    for (Element mapper : mapperList) {
      String resource = mapper.attributeValue("resource");
      InputStream stream = Resources.getResourceAsStream(resource);
      XmlMapperBuilder mapperBuilder = new XmlMapperBuilder(configuration);
      mapperBuilder.parse(stream);
    }
    return configuration;
  }
}
